package com.vidyu.businesslayer.businesscomponents.trackingmerger.impl;

import com.vidyu.businesslayer.businesscomponents.Constants;
import com.vidyu.businesslayer.businesscomponents.trackingmerger.SchedulerAPI;
import org.apache.log4j.Logger;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.JobDetailBean;
import org.springframework.stereotype.Component;

/**
 * Scheduler API - allow scheduling operations for beans using Quartz interface
 */

@Component
public class SchedulerAPIImpl implements SchedulerAPI {

    private static final Logger logger = Logger.getLogger(SchedulerAPIImpl.class);

    @Autowired
    private Scheduler scheduler;

    @Autowired
    private CronTrigger triggerBean;

    @Autowired
    private JobDetailBean fetchOnceJob;

    public boolean resumeFetchMainLoop(){
        try {
            scheduler.resumeTrigger(triggerBean.getName(), triggerBean.getGroup());
            return true;
        } catch (Exception e) {
           logger.fatal(e);
            return false;
        }
    }

    public boolean pauseFetchMainLoop(){
        try {
            scheduler.pauseTrigger(triggerBean.getName(), triggerBean.getGroup());
            return true;
        } catch (Exception e) {
            logger.fatal(e);
            return false;
        }
    }

    public boolean runFetchOnce(String test){
        try {
            Trigger simpleTrigger = TriggerUtils.makeImmediateTrigger(1,10000);
            JobDataMap jobDataMap = new JobDataMap();
            jobDataMap.put(Constants.TEST, test);
            simpleTrigger.setJobDataMap(jobDataMap);
            simpleTrigger.setName(Constants.ONE_TIME_TRIGGER);
            scheduler.scheduleJob(fetchOnceJob, simpleTrigger);
            return true;
        } catch (Exception e) {
            logger.fatal(e);
            return false;
        }
    }

}
